package.path = '/usr/local/Cellar/openresty/1.13.6.1/lualib/resty/?.lua;/opt/soft/nginx/lualib/resty/?.lua;'
package.cpath = '/usr/local/Cellar/openresty/1.13.6.1/lualib/?.so;/opt/soft/nginx/lualib/?.so;;'

local cjson = require "cjson"

local MYSQL_OPTS = {
	host = "agentrebate.db.58dns.org", 
    port = 4096, 
    database = "db58_agent_rebate", 
    user = "agentrebate_wr", 
    password = "2bcdb11d62ec2695", 
    charset = "utf8",
    max_package_size = 1024
}
function render(success, message, data)
	local res = {success=success, message=message, data=data}
	return cjson.encode(res)
end
function renderOK(message, data)
	return render(true, message, data)
end
function renderError(message, data)
	return render(false, message)
end
function executeSql(sql)
	local mysql = require "mysql"
    local db, err = mysql:new()
    if not db then
        return nil, ("failed to instantiate mysql: "..err)
    end

    db:set_timeout(1000)

    ngx.log(ngx.INFO, 'sql:'..sql)


    local ok, err, errno, sqlstate = db:connect(MYSQL_OPTS)

    if not ok then
        return nil, ("failed to connect: " .. err .. ": " .. errno .. " " .. sqlstate)
    end
    res, err, errno, sqlstate = db:query(sql)
    if not res then
        return nil, ("bad result: " .. err .. ": " .. errno .. ": " .. sqlstate)
    end
    db:close()

    return res
end

local res = ngx.location.capture('/userinfo')
local currUser = null
ngx.log(ngx.INFO, cjson.encode(res))
if res.status==200 then
	local resbody = cjson.decode(res.body)
	if  resbody.success then
		currUser = resbody.data
	else
		ngx.say(renderError('未登录!', null))
		return
	end
else
	ngx.say(renderError(cjson.encode(res), null))
	return
end	



local res, err = executeSql("select b.web_name,b.web_url,b.role_name from t_user_info a inner join t_role_info b on a.role_id=b.role_id where a.user_id='".. currUser.userName .."' group by b.web_name,b.web_url,b.role_name order by b.id")
if not res then
	ngx.log(ngx.ERR, err)
	ngx.say(renderError(err, null))
	return
end



if #res==0 then 
	ngx.say('{"success":true, "message":"无权限", "data":[]}')
	return
end

local topMenuIdx = {}
local menuArr = {}

for idx=1, #res do
	local item = res[idx];
	if not topMenuIdx[item.role_name] then
		topMenuIdx[item.role_name] = #menuArr+1

		menuArr[#menuArr+1] = {label = res[idx].role_name, children = {}}
	end
	
	local children = menuArr[topMenuIdx[item.role_name]].children
	children[#children+1] = {label = res[idx].web_name, url = res[idx].web_url}
end

ngx.say(renderOK('OK', menuArr))

